import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AppNetImage extends StatelessWidget {
  final String imageUrl;

  final Widget? placeholder;

  final Widget? errorWidget;

  final BoxFit? fit;

  final double? width;

  final double? height;
  final double? radius; //圆角
  final Color? borderColor; //边框颜色

  final double? placeHolderHeight;

  const AppNetImage({
    super.key,
    required this.imageUrl,
    this.placeholder,
    this.errorWidget,
    this.fit,
    this.width,
    this.height,
    this.placeHolderHeight,
    this.borderColor,
    this.radius,
  });

  @override
  Widget build(BuildContext context) {
    return ExtendedImage.network(
      imageUrl,
      width: width,
      height: height,
      fit: fit ?? BoxFit.cover,
      shape: BoxShape.rectangle,
      cache: true,
      border: Border.all(color: borderColor ?? Colors.transparent, width: 1.0),
      borderRadius: BorderRadius.all(Radius.circular(radius ?? 0)),
      clipBehavior: Clip.hardEdge,
      loadStateChanged: (ExtendedImageState state) {
        switch (state.extendedImageLoadState) {
          case LoadState.loading:
            return _loadingPlaceholder();
          case LoadState.completed:
            return null; // 显示原图
          case LoadState.failed:
            return GestureDetector(
              child: const Icon(Icons.error, color: Colors.red),
              onTap: () {
                state.reLoadImage(); // 点击重试
              },
            );
        }
      },
    );
  }

  Widget _loadingPlaceholder() {
    return const Image(image: AssetImage('assets/images/p1.png'));
  }

  Widget _errorPlaceholder() {
    return Container(
      width: width,
      height: height ?? 300.h,
      decoration: BoxDecoration(
        color: const Color.fromRGBO(231, 234, 236, 1),
        borderRadius: BorderRadius.all(Radius.circular(5.h)),
      ),
      child: Image.asset("assets/images/p1.png", fit: BoxFit.cover),
    );
  }
}
